# Vision Analyzer MCP Server Dockerfile
# Multi-stage build for optimal image size and security

# Stage 1: Build stage
FROM node:18-alpine AS builder

# Set build arguments
ARG BUILD_DATE
ARG VCS_REF
ARG VERSION

# Labels for build stage
LABEL maintainer="Vision Analyzer Team" \
      org.label-schema.build-date=$BUILD_DATE \
      org.label-schema.name="vision-analyzer" \
      org.label-schema.description="Vision Analyzer MCP Server" \
      org.label-schema.url="https://github.com/vision-analyzer/vision-analyzer" \
      org.label-schema.vcs-ref=$VCS_REF \
      org.label-schema.vcs-url="https://github.com/vision-analyzer/vision-analyzer.git" \
      org.label-schema.vendor="Vision Analyzer" \
      org.label-schema.version=$VERSION \
      org.label-schema.schema-version="1.0"

# Install build dependencies
RUN apk add --no-cache \
    git \
    python3 \
    make \
    g++ \
    && rm -rf /var/cache/apk/*

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm ci --only=production --ignore-scripts && \
    npm cache clean --force

# Stage 2: Runtime stage
FROM node:18-alpine AS runtime

# Set runtime arguments
ARG BUILD_DATE
ARG VCS_REF
ARG VERSION

# Security labels
LABEL maintainer="Vision Analyzer Team" \
      org.label-schema.build-date=$BUILD_DATE \
      org.label-schema.name="vision-analyzer" \
      org.label-schema.description="Vision Analyzer MCP Server" \
      org.label-schema.url="https://github.com/vision-analyzer/vision-analyzer" \
      org.label-schema.vcs-ref=$VCS_REF \
      org.label-schema.vcs-url="https://github.com/vision-analyzer/vision-analyzer.git" \
      org.label-schema.vendor="Vision Analyzer" \
      org.label-schema.version=$VERSION \
      org.label-schema.schema-version="1.0"

# Install runtime dependencies
RUN apk add --no-cache \
    dumb-init \
    curl \
    && rm -rf /var/cache/apk/*

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S visionanalyzer -u 1001 -G nodejs

# Set working directory
WORKDIR /app

# Copy dependencies from builder stage
COPY --from=builder --chown=visionanalyzer:nodejs /app/node_modules ./node_modules

# Copy application files
COPY --chown=visionanalyzer:nodejs . .

# Create necessary directories
RUN mkdir -p /app/logs /app/config /app/tmp && \
    chown -R visionanalyzer:nodejs /app/logs /app/config /app/tmp

# Set permissions
RUN chmod +x scripts/*.js

# Switch to non-root user
USER visionanalyzer

# Expose port
EXPOSE 3000

# Set environment variables
ENV NODE_ENV=production \
    PORT=3000 \
    UV_THREADPOOL_SIZE=16

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD node scripts/health-check.js || exit 1

# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]

# Start the application
CMD ["npm", "run", "start:production"]